package main

import (
	"fmt"
	"io/ioutil"

	//"io/ioutil"
	"net/http"

	"git.code.oa.com/mikemintang/webot"
)

// Example 机器人接入
func main() {
	http.HandleFunc("/entry", func(w http.ResponseWriter, req *http.Request) {
		bot := &webot.Bot{
			Token:      "pJdUREQeMiJyge3gITvMUI",
			AesKey:     "UBmd9hvkk2zcQ72asgzeHflptPaMMMvBfXVV6siinL4",
			WebhookURL: "http://relay.ifttt.oa.com/wechat-work/hook/cEpkVVJFUWVNaUp5Z2UzZ0lUdk1VSQ%3D%3D/VUJtZDlodmtrMnpjUTcyYXNnemVIZmxwdFBhTU1NdkJmWFZWNnNpaW5MNA%3D%3D/d59fa00f.f1955",
		}

		// 获取请求参数
		query := req.URL.Query()

		msgSign := query.Get("msg_signature")
		timestamp := query.Get("timestamp")
		nonce := query.Get("nonce")
		echoStr := query.Get("echostr")


		// 接入验证
		if echoStr != "" {
			decryptStr, err := bot.Valid(msgSign, timestamp, nonce, echoStr)
			if err != nil {
				fmt.Fprintf(w, "机器人接入验证失败："+err.Error())
				return
			}

			// 接入成功
			fmt.Fprintf(w, decryptStr)
			return
		}

		// 接收消息
		data, _ := ioutil.ReadAll(req.Body)
		msg, err := bot.DecryptMsg(msgSign, timestamp, nonce, data)

		if err != nil {
			fmt.Fprintf(w, "消息验证失败："+err.Error())
			return
		}

		// TODO: 消息处理

		// 主动推送消息:
		//bot.Text("机器人主动推送：").Send()
		// 被动回复消息
		rmsg, _ := bot.Text(fmt.Sprintf("接收到消息：%+v", msg)).Reply()

		fmt.Fprintf(w, string(rmsg))
	})

	http.ListenAndServe(":8097", nil)

	// Output: xxx
}